const spider = require('./tools/spider');
const { formatDate } = require('./tools/formatDate');
const { formatUserName } = require('./tools/formatUserInfo');
const { getWinnerNum, judgeUserIsInGameSeat, parseNumber, getArrayIndex } = require('./utils/util');
const { log } = require('./utils/log');

let formatStart = null; // ex: [ '2020-04-28', '2020-04-28 23:58:37', 1588089517 ]
let formatEnd = null;
let userListJson = [];
let gameListJson = [];
let simpleUserlistJson = [];

// 初始化数据
let initData = () => {
  formatStart = null;
  formatEnd = null;
  userListJson = [];
  gameListJson = [];
  simpleUserlistJson = [];
};

// 获取用户信息
let getUserList = async type => {
  log('获取用户列表信息');
  let userlistres = await spider.getUserList(type);
  userListJson = await formatUserName(userlistres);
};

// 获取用户简要信息
let getSimpleUserList = async () => {
  log('-> 获取用户简要信息');
  userListJson.forEach(item => {
    const { gameuserid, headimg, formatUserName } = item;
    let score = '0';
    let finalScore = 0;
    let origin = '0';
    const obj = {
      gameuserid,
      headimg,
      formatUserName,
      score,
      finalScore,
      origin
    };
    simpleUserlistJson.push(obj);
  });
};

// 获取赛事信息
let getGameList = async (type, time) => {
  log('-> 获取赛事列表信息');
  let res = await spider.getGameList(type, time);
  // 排序
  const sortGameListArr = res.sort((a, b) => a.setletcreatetime - b.setletcreatetime);
  gameListJson.push(...sortGameListArr);
  log('<- 获取赛事列表信息', gameListJson.length);
};

// 按时间过滤赛事结果
let filterGameListByTime = async () => {
  let start = formatStart[2];
  let end = formatEnd[2];
  let startIndex = getArrayIndex(gameListJson, start);
  let endIndex = getArrayIndex(gameListJson, end);
  let filterArr = gameListJson.slice(startIndex, endIndex + 1);
  gameListJson = filterArr;
  // 格式化打印
  const printGameListJson = gameListJson
    .map(item => {
      const { setletcreatetime } = item;
      const [date, time] = formatDate(setletcreatetime); // [ '2020-04-28', '2020-04-28 23:58:37' ]
      Object.assign(item, { date, time });
      return JSON.stringify(item);
    })
    .join('\n')
    .toString();
  log(startIndex, endIndex, '过滤游戏结果长度', gameListJson.length, '\n', printGameListJson);
};

// 模块费用统计
const FeeMap = {
  majiang: {
    times: 1,
    fee: 6,
    minScore: 10
  },
  ddz: {
    times: 1,
    fee: 5,
    minScore: 6
  }
};

// 遍历赛事数据统计结果
let getFinalGameList = async type => {
  gameListJson.forEach(gameItem => {
    const { seats } = gameItem;
    // 获取模块扣分规则
    const FeeScore = FeeMap[type];
    // 1.获取大赢家数量
    let totalWinner = getWinnerNum(seats);
    let fee = FeeScore.fee / totalWinner;
    // 2.循环 更新数据
    simpleUserlistJson.forEach(userItem => {
      let res = judgeUserIsInGameSeat(userItem.gameuserid, seats);
      if (res) {
        const { score, totalscore, iswiner } = res;
        if (iswiner) {
          if (score >= 0 && score <= FeeScore.minScore) fee = 0; // 赢钱 小于 minScore 不交房费
          if (totalWinner === 1 && score <= FeeScore.minScore) fee = 0; // 一个大赢家时  分数<= minScore 不扣房费
          let number = score - fee;
          userItem.score += parseNumber(number);
          userItem.finalScore += Number(number);
          userItem.origin += parseNumber(score);
        } else {
          userItem.score += parseNumber(score);
          userItem.finalScore += Number(score);
          userItem.origin += parseNumber(score);
        }
      }
    });
  });
  // 最后数组排序  finalScore 从高到低
  simpleUserlistJson.sort((a, b) => b.finalScore - a.finalScore);
  return simpleUserlistJson;
};

let entry = async (req, res) => {
  // 初始化数据
  initData();
  // 计算数据 type: ddz、majiang
  const { type, start, end } = req.body;
  if (start > end) {
    const ret = JSON.stringify({ code: -1, msg: '时间输入错误' });
    res.end(ret);
    return;
  }
  formatStart = formatDate(start);
  formatEnd = formatDate(end);
  log('\n', formatStart, '\n', formatEnd);

  await getUserList(type); // 拉取用户数据
  await getSimpleUserList(type);
  await getGameList(type, formatStart[0]);

  if (formatEnd[0] !== formatStart[0]) await getGameList(type, formatEnd[0]);

  await filterGameListByTime();
  let result = await getFinalGameList(type);

  const ret = JSON.stringify({ code: 0, msg: '获取结果成功', data: result });
  res.end(ret);
};

module.exports = { entry };
